<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="设备类型" name="typeId">
						<a-select
							v-model:value="searchFormState.typeId"
							placeholder="请选择设备类型"
							:options="typeOptions"
							@change="onTypeChange"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="设备名称" name="deviceName">
						<a-input v-model:value="searchFormState.deviceName" placeholder="请输入设备名称" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="用户名" name="userName">
						<a-input v-model:value="searchFormState.userName" placeholder="请输入预约用户名称" />
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="日期" name="reservationDate">
						<a-range-picker v-model:value="searchFormState.reservationDate" />
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="时间段" name="timeSlot">
						<a-input v-model:value="searchFormState.timeSlot" placeholder="请输入时间段" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="预约状态" name="status">
						<a-select v-model:value="searchFormState.status" placeholder="请选择预约状态" :options="statusOptions" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
					<a @click="toggleAdvanced" style="margin-left: 8px">
						{{ advanced ? '收起' : '展开' }}
						<component :is="advanced ? 'up-outlined' : 'down-outlined'" />
					</a>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('userReservationAdd')">
						<template #icon><plus-outlined /></template>
						新增
					</a-button>
					<xn-batch-button
						v-if="hasPerm('userReservationBatchDelete')"
						buttonName="批量删除"
						icon="DeleteOutlined"
						buttonDanger
						:selectedRowKeys="selectedRowKeys"
						@batchCallBack="deleteBatchUserReservation"
					/>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="formRef.onOpen(record)" v-if="hasPerm('userReservationEdit')">编辑</a>
						<a-divider type="vertical" v-if="hasPerm(['userReservationEdit', 'userReservationDelete'], 'and')" />
						<a-popconfirm
							:title="
								record.status === '已完成' || record.status === '已取消' ? '确定要删除吗？' : '确定要取消该预约吗？'
							"
							@confirm="deleteUserReservation(record)"
						>
							<a-button
								type="link"
								danger
								size="small"
								v-if="hasPerm('userReservationDelete')"
								:disabled="
									record.status === '已批准' ? false : !(record.status === '已取消' || record.status === '已完成')
								"
							>
								{{ record.status === '已取消' || record.status === '已完成' ? '删除' : '取消预约' }}
							</a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="tableRef.refresh()" />
</template>

<script setup name="userReservation">
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import Form from './form.vue'
	import userReservationApi from '@/api/biz/userReservationApi'
	import deviceReservationApi from '@/api/biz/deviceReservationApi'
	import bizDictApi from '@/api/biz/bizDictApi'
	import deviceTimeApi from '@/api/biz/deviceTimeApi'
	import bizUserApi from '@/api/biz/bizUserApi'
	import deviceTypeApi from '@/api/biz/deviceTypeApi'

	const searchFormState = ref({})
	const searchFormRef = ref()
	const tableRef = ref()
	const formRef = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	// 查询区域显示更多控制
	const advanced = ref(false)
	const toggleAdvanced = () => {
		advanced.value = !advanced.value
	}
	const columns = [
		{
			title: '设备类型',
			dataIndex: 'typeName'
		},
		{
			title: '设备名称',
			dataIndex: 'deviceName'
		},
		{
			title: '预约日期',
			dataIndex: 'reservationDate'
		},
		{
			title: '预约时间段',
			dataIndex: 'timeSlot'
		},
		{
			title: '预约用户',
			dataIndex: 'userName'
		},
		{
			title: '预约状态',
			dataIndex: 'status',
			customRender: ({ text }) => {
				if (text === '已批准') {
					return h('span', { style: { color: '#52c41a' } }, text)
				} else if (text === '已完成') {
					return h('span', { style: { color: '#bfbfbf' } }, text)
				} else if (text === '已取消') {
					return h('span', { style: { color: '#f59293' } }, text)
				} else {
					return text
				}
			}
		}
	]
	// 操作栏通过权限判断是否显示
	if (hasPerm(['userReservationEdit', 'userReservationDelete'])) {
		columns.push({
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: 150
		})
	}
	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		// columns数字类型字段加入 needTotal: true 可以勾选自动算账
		alert: {
			show: true,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const typeOptions = ref([])

	// 获取设备类型
	const getType = () => {
		deviceTypeApi.getAll().then((res) => {
			typeOptions.value = res.map((orgNode) => {
				const groupOption = {
					label: orgNode.name,
					disabled: true, // 禁用机构节点
					style: {
						fontWeight: 'bold',
						backgroundColor: '#f5f5f5'
					},
					options: []
				}
				if (orgNode.children && orgNode.children.length > 0) {
					groupOption.options = orgNode.children.map((typeNode) => ({
						label: typeNode.name,
						value: typeNode.id,
						disabled: false
					}))
				}

				return groupOption
			})
		})
	}

	const loadData = (parameter) => {
		typeOptions.value = getType()
		const searchFormParam = cloneDeep(searchFormState.value)
		// reservationDate范围查询条件重载
		if (searchFormParam.reservationDate) {
			searchFormParam.startReservationDate = searchFormParam.reservationDate[0]
			searchFormParam.endReservationDate = searchFormParam.reservationDate[1]
			delete searchFormParam.reservationDate
		}
		return userReservationApi.userReservationPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		tableRef.value.refresh(true)
	}
	// 删除 + 取消预约
	const deleteUserReservation = (record) => {
		if (record.status === '已完成' || record.status === '已取消') {
			let params = [
				{
					id: record.id
				}
			]
			deviceReservationApi.deviceReservationDelete(params).then(() => {
				tableRef.value.refresh(true)
			})
		} else {
			let param = {
				id: record.id
			}
			deviceReservationApi.cancel(param).then(() => {
				tableRef.value.refresh(true)
			})
		}
	}
	// 批量删除
	const deleteBatchUserReservation = (params) => {
		deviceReservationApi.deviceReservationDelete(params).then(() => {
			tableRef.value.clearRefreshSelected()
		})
	}
	const timeSlotOptions = ref([])
	const filteredTimeSlotOptions = ref([])

	// 初始化所有时间段选项
	bizDictApi.treeByDict({ dictName: 'TIME_SLOT' }).then((res) => {
		timeSlotOptions.value = res.map((item) => {
			return {
				label: item.dictLabel,
				value: item.dictValue
			}
		})
		// 默认显示所有时间段
		filteredTimeSlotOptions.value = [...timeSlotOptions.value]
	})

	// 用设备类型换取所有时间段
	const getTimeByType = (typeId) => {
		return deviceTimeApi
			.getDeviceTimeByType(typeId)
			.then((res) => {
				// 根据返回的时间段列表过滤选项
				if (res && Array.isArray(res)) {
					filteredTimeSlotOptions.value = timeSlotOptions.value.filter((option) => res.includes(option.value))
				} else {
					filteredTimeSlotOptions.value = []
				}
				return res
			})
			.catch((error) => {
				console.error('获取设备时间段失败:', error)
				// 出错时显示所有时间段
				filteredTimeSlotOptions.value = [...timeSlotOptions.value]
			})
	}

	// 设备类型改变时的处理
	const onTypeChange = (typeValue) => {
		// 清空时间段选择
		searchFormState.value.timeSlot = undefined

		if (typeValue) {
			// 根据设备类型获取对应的时间段
			getTimeByType(typeValue)
		} else {
			// 如果没有选择设备类型，显示所有时间段
			filteredTimeSlotOptions.value = [...timeSlotOptions.value]
		}
	}
	const statusOptions = tool.dictList('RESERVATION')
</script>
